package com.jds.test.http;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpRequestDecoder;
import io.netty.handler.codec.http.HttpResponseEncoder;
import io.netty.handler.codec.http.HttpServerCodec;

/**
 * Initializer
 *
 * @author shane
 */
public class HttpServerInitializer extends ChannelInitializer<SocketChannel> {

    private HttpServerHandler handler;

    public HttpServerInitializer(HttpServerHandler handler) {
        this.handler = handler;
    }

    @Override
    public void initChannel(SocketChannel ch) throws Exception {

        ChannelPipeline pipeline = ch.pipeline();

//        // decode 1 byte2http解码器
//        pipeline.addLast(new HttpRequestDecoder());
//
//        // encode last 1 http2byte编码器
//        pipeline.addLast(new HttpResponseEncoder());
        pipeline.addLast(new HttpServerCodec());
        pipeline.addLast(new HttpObjectAggregator(65535));

        // endoe last 2 body2full编码器
        pipeline.addLast(new BodyToResponseEncoder());

        // decode 2 full2body编码器
        pipeline.addLast(new RequestToBodyDecoder());

        // 业务处理Handler
        pipeline.addLast("httpServerHandler", handler);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        super.exceptionCaught(ctx, cause);
    }
}
